package com.ws.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ws.entity.Goods;
import com.ws.mapper.GoodsMapper;
import com.ws.service.GoodsService;
import com.ws.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Result getGoodsListForPage(String name, Long goodsTypeId, Integer isOnSale, int pno, int psize) {

        Page<Goods> p = new Page<>(pno, psize);
        Page<Goods> pageResult = goodsMapper.getGoodsListForPage(p, name, goodsTypeId, isOnSale);
        List<Goods> goodsList = pageResult.getRecords();

        //从分页中提取数据
        JSONObject data = new JSONObject();
        data.put("list",goodsList);

        //传入分页相关参数
        JSONObject page = new JSONObject();
        page.put("pno",pno);
        page.put("psize",psize);
        page.put("pCount",pageResult.getPages());
        page.put("totalElements",pageResult.getTotal());
        data.put("page",page);
        return Result.end(200, data, "查询成功");
    }

    @Override
    public Result insertGoods(Goods goods) {
        //设置初始值
        //默认下架
        goods.setIsOnSale(0);
        goods.setInsertTime(new Date());
        goods.setSaleCount(0);
        int count = goodsMapper.insert(goods);
        if(count > 0) {
            return Result.end(200,"","增加成功");
        }
        return Result.end(500,"","增加失败");
    }

    @Override
    public Result findGoodsById(Long id) {
        Goods goods = goodsMapper.selectById(id);
        return Result.end(200,goods,"查询成功");
    }

    @Override
    public Result updateGoods(Goods goods) {
        int count = goodsMapper.updateById(goods);
        if(count > 0) {
            return Result.end(200,"","增加成功");
        }
        return Result.end(500,"","增加失败");
    }

    @Override
    public Result deleteGoodsById(Long id) {
        int count = goodsMapper.deleteById(id);
        if(count > 0) {
            return Result.end(200,"","删除成功");
        }
        return Result.end(500,"","删除失败");
    }

    @Override
    public Result setGoodsOnsale(Long id, Integer isOnSale) {
        Goods goods = goodsMapper.selectById(id);
        goods.setIsOnSale(isOnSale);
        int count = goodsMapper.updateById(goods);
        if(count > 0) {
            return Result.end(200,"","设置成功");
        }
        return Result.end(500,"","设置失败");
    }

    @Override
    public Result getHotGoods() {
        List<Goods> hotGoodsList =  goodsMapper.getHotGoods();
        JSONObject data = new JSONObject();
        data.put("list",hotGoodsList);
        return Result.end(200,data,"succ");
    }


}
